import string
import logging
import redis
import random


from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password, check_password
from captcha.image import ImageCaptcha
from django.http import HttpResponse

from .models import *
from user.serializer import *
from util.ronglianyun import send_message
from util.jwt_token import MyJwt
from django.conf import settings
from django.core.paginator import Paginator
from util.ip_address.ip_info import CzIp


# 分页函数
def pag(self, userinfo, pag_size, pagination):
    paginator = Paginator(userinfo, pag_size)

    page = paginator.page(pagination)

    return page


# 短信验证码
class SendCode(ViewSet):
    def sms_code(self, request):
        mobile = request.data.get('mobile')

        r = redis.Redis(host='localhost', port=6379, db=0)
        sms_code = random.randint(10000, 99999)

        print('sms_code:', sms_code)

        result = send_message(sms_code, mobile)

        sms_key = 'sms_%s' % mobile
        r.setex(sms_key, 300, sms_code)

        return Response({'code': 200, 'msg': '短信验证码发送成功'})


# 校验数据
class Check:
    # 账号数据校验
    def check_account(self, account):
        #  账号以字母数字下划线组成 是四到十五位
        if not re.findall(r'^[a-zA-Z][a-zA-Z0-9_]{4,15}$', account):
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '账号格式不正确'})

        user = UserModel.objects.filter(account=account, is_delete=False).first()
        if user:
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '账号已经存在'})

    # 手机号数据校验
    def check_mobil(self, mobile):
        # 手机号以1开头, 第二位3 - 9 之间的数字，长度为11, 只允许数字
        if not re.findall(r"^1[3-9]\d{9}$", mobile):
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '手机号不合法'})

        user = UserModel.objects.filter(mobile=mobile, is_delete=False).first()
        if user:
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '手机号已经存在'})

    # 邮箱数据校验
    def check_email(self, email):
        # 校验邮箱
        if not re.findall(r'^[1-9][0-9]{4,10}@qq.com$', email):
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '邮箱不合法'})

        user = UserModel.objects.filter(email=email, is_delete=False).first()
        if user:
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '邮箱已经存在'})

    def chech_name(self, name):
        if not re.findall(r"^[\u4e00-\u9fa5\w]{1,9}$", name):
            raise Response(f'{name} 姓名由2到10位汉字、数字、字母或下划线组成！')


# 图片验证码 入职 登录 忘记密码 获取ip
class UserView(ViewSet):

    # 获取ip
    def gain_ip(self, request):
        ip = ''
        try:
            # HTTP_X_FORWARDED_FOR: 浏览当前页面的用户计算机的网关.
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                # REMOTE_ADDR: 浏览当前页面的用户计算机的ip地址
                ip = request.META.get('REMOTE_ADDR')
        except Exception as e:
            logging.info("request user IP address failed. error msg:{}".format(e))
        return ip

    # 图片验证码
    def img(self, request, uuid):

        number = string.ascii_letters + string.digits
        img_code = "".join(random.sample(number, 4))
        print("img_code", img_code)
        img_ser = ImageCaptcha()
        img_code_num = img_ser.generate(img_code)
        redis_conn = redis.Redis(host='localhost', port=6379, db=0)
        # 根据uuid构造key
        key = "img:%s" %uuid
        # 设置过期时间
        redis_conn.set(key, img_code, ex=300)
        # 关闭
        redis_conn.close()
        return HttpResponse(img_code_num, content_type="image/png")

    # 员工入职
    def reg(self, request):
        name = request.data.get("uname")
        account = request.data.get("username")
        mobile = request.data.get("mobile")
        password = request.data.get("password")
        email = request.data.get("email")

        # 角色
        role = request.data.get("rolename")
        # 职位
        position = request.data.get("position")
        # 职级
        rank = request.data.get("grade")
        # 部门
        department = request.data.get("department")
        print("数据", request.data)

        if not all([name, account, password, role, position, rank, department]):
            return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "数据不全，不可入职！！！"})

        check = Check()
        check.check_account(account)
        check.check_mobil(mobile)
        check.chech_name(name)

        user = UserModel.objects.filter(account=account)
        if user:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "账号已经存在"})

        try:
            pwd = make_password(password)
            position = PositionModel.objects.filter(dept=department).count()
            if position != 0:
                position = PositionModel.objects.filter(dept=department, rank=rank).first()
                position_ser = PositionSer(position)

                UserModel.objects.create(name=name, mobile=mobile, password=pwd, account=account,
                                     email=email, position_id=position_ser.data['id'])
                role = RoleModel.objects.filter(id=role).first()
                ser = RoleSer(role)
                PositionRoleModel.objects.create(position_id=position_ser.data['id'], role_id=ser.data['id'])
            return Response({'code': status.HTTP_200_OK, 'msg': '入职成功'})
        except Exception as e:
            print(str(e))
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, 'msg': '服务器错误'})

    # 员工登录
    def login(self, request,uuid):

        name = request.data.get("name")
        password = request.data.get("password")
        image_code = request.data.get("code")

        if not all([name, password]):
            return Response({"code": 400, "msg": "数据不全，不可登录！！！"})

        check = Check()
        check.chech_name(name)

        user = UserModel.objects.filter(name=name, is_delete=False).first()

        if not user:
            return Response({"code": 400, "msg": "没有此员工！！"})
        else:
            if check_password(password, user.password):

                key = "img:%s" % uuid
                redis_conn = redis.Redis(host='localhost', port=6379, db=0)
                code = redis_conn.get(key)

                if not code:
                    return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "图片验证码过期"})
                print("验证码:", code)

                if code.decode() == image_code:
                    myjwt = MyJwt()
                    ser = UserSer(user)

                    ip = self.gain_ip(request)
                    # 获取登陆的设备
                    device = request.headers.get("User-Agent")
                    # 获取登陆地址
                    cz = CzIp()
                    places = cz.get_addr_by_ip(ip)
                    print(places)
                    ConLogModel.objects.create(ip=ip, device=device, user_id=user.id,address=places)

                    # 添加操作日志
                    ULogModel.objects.create(user_id=user.id, action="登录", path='/login/')

                    return Response({"code": status.HTTP_200_OK, "msg": "登录成功!", "token": myjwt.encode({'id': user.id, "name": user.name}), "data": ser.data})

                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "图片验证失败"})

        return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg": "用户名或密码错误！"})

    # 忘记密码 有短信验证码
    def upuser(self, request):
        try:
            name = request.data.get("name")
            mobile = request.data.get("mobile")
            password = request.data.get("password")
            code = request.data.get("code")

            redis_conn = redis.Redis(host='localhost', port=6379, db=0)
            sms_key = 'sms_%s' % mobile
            stored_sms_code = redis_conn.get(sms_key)

            try:

                if stored_sms_code.decode() != code:
                    return Response({'code': '204', 'msg': '验证码过期或者错误'})

                user = UserModel.objects.filter(name=name, is_delete=False)

                if not user:
                    return Response({'code': 400, 'msg': '用户不存在'})

                if name:
                    user.update(name=name)
                if mobile:
                    user.update(mobile=mobile)
                if password:
                    hash_pwd = make_password(password, "pbkdf2_sha256")
                    user.update(password=hash_pwd)
                return Response({'code': 200, 'msg': '修改成功'})
            except Exception as e:
                print('失败的原因：', str(e))
                return Response({'code': 400, 'msg': '修改失败'})

        except Exception as e:
            print('修改失败的原因', e)
            return Response({"code": 500, "msg": "服务器错误"})

    # 忘记密码
    def upusers(self, request):
        try:
            account = request.data.get("name")
            password = request.data.get("password")

            if not all([account, password]):
                return Response({"code": status.HTTP_204_NO_CONTENT, "msg": "用户名和密码不能为空"})

            try:
                user = UserModel.objects.filter(account=account, is_delete=False)

                if not user:
                    return Response({'code': 400, 'msg': '用户不存在'})
                check = Check()
                check.check_account(account)
                if account:
                    user.update(account=account)
                if password:
                    hash_pwd = make_password(password, "pbkdf2_sha256")
                    user.update(password=hash_pwd)
                return Response({'code': 200, 'msg': '修改成功'})
            except Exception as e:
                print('失败的原因：', str(e))
                return Response({'code': 400, 'msg': '修改失败'})


        except Exception as e:
            print('修改失败的原因', e)
            return Response({"code": 500, "msg": "服务器错误"})




